<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 5] 5.8 Interfaces</TITLE>
<META NAME="author" CONTENT="Pat Niemeyer and Josh Peck">
<META NAME="date" CONTENT="Tue Jul 22 18:52:58 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Exploring Java">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Exploring Java" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_07.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 5<br>Objects in Java</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch05_09.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-8">5.8 Interfaces</A></h2>

<P CLASS=para>
<A NAME="CH05.INTER1"></A>Interfaces are kind of like Boy Scout (or Girl Scout) merit badges. When 
a scout has learned to build a bird house, he can walk around wearing a 
little patch with a picture of one on his sleeve. This says to the world, 
"I know how to build a bird house." Similarly, an <I CLASS=emphasis>interface</I> 
is a list of methods that define some set of behavior for an object. Any 
class that implements each of the methods listed in the interface can declare 
that it implements the interface and wear, as its merit badge, an extra 
type--the interface's type. 

<P CLASS=para>
Interface types act like class types. You can declare variables to 
be of an interface type, you can declare arguments of methods to accept 
interface types, and you can even specify that the return type of a method 
is an interface type. In each of these cases, what is meant is that any 
object that implements the interface (i.e., wears the right merit badge) 
can fill that spot. In this sense, interfaces are orthogonal to the class 
hierarchy. They cut across the boundaries of what kind of object an item 
is and deal with it only in terms of what it can do. A class implements 
as many interfaces as it desires. In this way, interfaces in Java replace 
the need for multiple inheritance (and all of its messy side effects). 

<P CLASS=para>
An interface looks like a purely <tt CLASS=literal>abstract</tt> class 
(i.e., a class with only <tt CLASS=literal>abstract</tt> methods). You 
define an interface with the <tt CLASS=literal>interface</tt> keyword 
and list its methods with no bodies: 

<DIV CLASS=programlisting>
<P>
<PRE>
interface Driveable { 
    boolean startEngine(); 
    void stopEngine(); 
    float accelerate( float acc ); 
    boolean turn( Direction dir ); 
} 
</PRE>
</DIV>

<P CLASS=para>
The example above defines an interface called
<tt CLASS=literal>Driveable</tt> with four methods. It's acceptable, but
not necessary, to declare the methods in an interface with the
<tt CLASS=literal>abstract</tt> modifier, so we haven't used it
here. Interfaces define capabilities, so it's common to name
interfaces after their capabilities in a passive
sense. "Driveable" is a good example; "runnable" and
"updateable" would be two more.

<P CLASS=para>
Any class that implements all the methods can then declare it implements 
the interface by using a special <tt CLASS=literal>implements</tt> clause 
in its class definition: 

<DIV CLASS=programlisting>
<P>
<PRE>
class Automobile implements Driveable { 
    ... 
    boolean startEngine() { 
        if ( notTooCold ) 
            engineRunning = true; 
        ... 
    } 
 
    void stopEngine() { 
        engineRunning = false; 
    } 
 
    float accelerate( float acc ) { 
        ... 
    } 
 
    boolean turn( Direction dir ) { 
        ... 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
The class <tt CLASS=literal>Automobile</tt> implements the methods of the
<tt CLASS=literal>Driveable</tt> interface and declares itself
<tt CLASS=literal>Driveable</tt> using an <tt CLASS=literal>implements</tt>
clause.

<P CLASS=para>
As shown in <A HREF="ch05_08.htm#EXJ-CH-5-FIG-10">Figure 5.9</A>, another class,
such as <tt CLASS=literal>LawnMower</tt>, can also implement the
<tt CLASS=literal>Driveable</tt> interface. The figure illustrates the
<tt CLASS=literal>Driveable</tt> interface being implemented by two
different classes. While it's possible that both
<tt CLASS=literal>Automobile</tt> and <tt CLASS=literal>Lawnmower</tt> could
derive from some primitive kind of vehicle, they don't have to
in this scenario. This is a significant advantage of interfaces over
standard multiple inheritance as implemented in C++.

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="EXJ-CH-5-FIG-10">Figure 5.9: Implementing the Driveable interface</A></h4>


<p>
<img align=middle src="./figs/je0510.gif" alt="[Graphic: Figure 5-9]" width=503 height=303 border=0>

</DIV>

<P CLASS=para>
After declaring the interface, we have a new type,
<tt CLASS=literal>Driveable</tt>.  We can declare variables of type
<tt CLASS=literal>Driveable</tt> and assign them any instance of a
<tt CLASS=literal>Driveable</tt> object:

<DIV CLASS=programlisting>
<P>
<PRE>
Automobile auto = new Automobile(); 
Lawnmower mower = new Lawnmower(); 
Driveable vehicle; 
 
vehicle = auto; 
vehicle.startEngine(); 
vehicle.stopEngine(); 
... 
vehicle = mower; 
vehicle.startEngine(); 
vehicle.stopEngine(); 
</PRE>
</DIV>

<P CLASS=para>
Both <tt CLASS=literal>Automobile</tt> and <tt CLASS=literal>Lawnmower</tt> 
implement <tt CLASS=literal>Driveable</tt> and can be considered of 
that type.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-8.1">Interfaces as Callbacks</A></h3>

<P CLASS=para>
<A NAME="CH05.CALL"></A><A NAME="CH05.CALL2"></A>Interfaces can be used to implement callbacks in Java. A <I CLASS=emphasis>callback</I> 
is a situation where you'd like to pass a reference to some behavior 
and have another object invoke it later. In C or C++, this is prime territory 
for function pointers; in Java, we'll use interfaces instead. 

<P CLASS=para>
Consider two classes: a <tt CLASS=literal>TickerTape</tt> class that 
displays data and a <tt CLASS=literal>TextSource</tt> class that provides 
an information feed. We'd like our <tt CLASS=literal>TextSource</tt> 
to send any new text data. We could have <tt CLASS=literal>TextSource</tt> 
store a reference to a <tt CLASS=literal>TickerTape</tt> object, but 
then we could never use our <tt CLASS=literal>TextSource</tt> to send 
data to any other kind of object. Instead, we'd have to proliferate 
subclasses of <tt CLASS=literal>TextSource</tt> that dealt with different 
types. A more elegant solution is to have <tt CLASS=literal>TextSource</tt> 
store a reference to an interface type, <tt CLASS=literal>TextUpdateable</tt>: 

<DIV CLASS=programlisting>
<P>
<PRE>
interface TextUpdateable { 
    receiveText( String text ); 
} 
 
class TickerTape implements TextUpdateable { 
    TextSource source; 
 
    init() { 
        source = new TextSource( this ); 
        ... 
    } 
 
    public receiveText( String text ) { 
        scrollText( text ): 
    } 
    ... 
} 
 
class TextSource { 
    TextUpdateable receiver; 
 
    TextSource( TextUpdateable r ) { 
        receiver = r; 
    } 
 
    private sendText( String s ) { 
        receiver.receiveText( s ); 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
The only thing <tt CLASS=literal>TextSource</tt> really cares about 
is finding the right method to invoke to send text. Thus, we can list that 
method in an interface called <tt CLASS=literal>TextUpdateable</tt> 
and have our <tt CLASS=literal>TickerTape</tt> implement the interface. 
A <tt CLASS=literal>TickerTape</tt> object can then be used anywhere we need something of the type <tt CLASS=literal>TextUpdateable</tt>. 
In this case, the <tt CLASS=literal>TextSource</tt> constructor takes 
a <tt CLASS=literal>TextUpdateable</tt> object and stores the reference 
in an instance variable of type <tt CLASS=literal>TextUpdateable</tt>. 
Our <tt CLASS=literal>TickerTape</tt> object simply passes a reference 
to itself as the callback for text updates, and the source can invoke its 
<tt CLASS=literal>receiveText()</tt> method as necessary. 

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-8.2">Interface Variables</A></h3>

<P CLASS=para>
<A NAME="CH05.VAR"></A>Although interfaces allow us to specify behavior without 
implementation, there's one exception. An interface can contain constant 
variable identifiers; these identifiers appear in any class that implements 
the interface. This functionality allows for predefined parameters that 
can be used with the methods: 

<DIV CLASS=programlisting>
<P>
<PRE>
interface Scaleable { 
    static final int BIG = 0, MEDIUM = 1, SMALL = 2; 
 
    void setScale( int size ); 
} 
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>Scaleable</tt> interface defines three integers: 
<tt CLASS=literal>BIG</tt>, <tt CLASS=literal>MEDIUM</tt>, and <tt CLASS=literal>SMALL</tt>. 
All variables defined in interfaces are implicitly <tt CLASS=literal>final</tt> 
and <tt CLASS=literal>static</tt>; we don't have to use the 
modifiers here but, for clarity, we recommend you do so. 

<P CLASS=para>
A class that implements <tt CLASS=literal>Scaleable</tt> sees these 
variables: 

<DIV CLASS=programlisting>
<P>
<PRE>
class Box implements Scaleable { 
 
    void setScale( int size ) { 
        switch( size ) { 
            case BIG: 
                ... 
            case MEDIUM: 
                ... 
            case SMALL: 
                ... 
        } 
    } 
    ... 
} 
</PRE>
</DIV>

<DIV CLASS=sect3>
<h4 CLASS=sect3><A CLASS="TITLE" NAME="ch05-SECT3-AUTOID.5">Empty Interfaces</A></h4>

<P CLASS=para>
Sometimes, interfaces are created just to hold constants; anyone who 
implements the interfaces can see the constant names, much as if they were
included by a C/C++ include file.  This is a somewhat degenerate, but 
acceptable use of interfaces.

<P CLASS=para>
Sometimes completely empty interfaces will be used to serve as a marker
that a class has some special property.  The java.io.Serializeable interface
is a good example (See Chapter 8).  Classes that implement Serializable don't 
add any methods or variables.  Their additional type simply identifies them 
to Java as classes that want to be able to be serialized.

</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-8.3">Interfaces and Packages</A></h3>

<P CLASS=para>
Interfaces behave like classes within packages. An interface can be declared 
<tt CLASS=literal>public</tt> to make it visible outside of its package. 
Under the default visibility, an interface is visible only inside of its 
package. There can be only one <tt CLASS=literal>public</tt> interface 
declared in a compilation unit. 

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-8.4">Subinterfaces</A></h3>

<P CLASS=para>
An interface can extend another interface, just as a class can extend another 
class. Such an interface is called a <I CLASS=emphasis>subinterface</I>: 

<DIV CLASS=programlisting>
<P>
<PRE>
interface DynamicallyScaleable extends Scaleable { 
    void changeScale( int size ); 
} 
</PRE>
</DIV>

<P CLASS=para>
The interface <tt CLASS=literal>DynamicallyScaleable</tt> extends our 
previous <tt CLASS=literal>Scaleable</tt> interface and adds an additional 
method. A class that implements <tt CLASS=literal>DynamicallyScaleable</tt> 
must implement all methods of both interfaces. 

<P CLASS=para>
Interfaces can't specify that they implement other interfaces, instead they
are allowed to extend more than one interface.  (This is multiple inheritence
for interfaces).  More than one superinterface can be specified with the 
comma operator:

<DIV CLASS=programlisting>
<P>
<PRE>
    interface DynamicallyScaleable extends Scaleable, SomethingElseable {
        ...
</PRE>
</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-9.4">Inside Arrays</A></h3>

<P CLASS=para>
<A NAME="CH05.ARRAYS"></A>At the end of <A HREF="ch04_01.htm">Chapter 4, <i>The Java Language</i></A>, I mentioned that arrays have a 
place in the Java class hierarchy, but I didn't give you any details. 
Now that we've discussed the object-oriented aspects of Java, I can 
give you the whole story. 

<P CLASS=para>
Array classes live in a parallel Java class hierarchy under the <tt CLASS=literal>Object</tt> 
class. If a class is a direct subclass of <tt CLASS=literal>Object</tt>, 
then an array class for that base type also exists as a direct subclass 
of <tt CLASS=literal>Object</tt>. Arrays of more derived classes are 
subclasses of the corresponding array classes. For example, consider the 
following class types: 

<DIV CLASS=programlisting>
<P>
<PRE>
class Animal { ... } 
class Bird extends Animal { ... } 
class Penguin extends Bird { ... } 
</PRE>
</DIV>

<P CLASS=para>
<A HREF="ch05_08.htm#EXJ-CH-5-FIG-11">Figure 5.10</A> illustrates the class hierarchy for arrays 
of these classes. 

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="EXJ-CH-5-FIG-11">Figure 5.10: Arrays in the Java class hierarchy</A></h4>


<p>
<img align=middle src="./figs/je0511.gif" alt="[Graphic: Figure 5-10]" width=503 height=238 border=0>

</DIV>

<P CLASS=para>
Arrays of the same dimension are related to one another in the same manner 
as their base type classes. In our example, <tt CLASS=literal>Bird</tt> 
is a subclass of <tt CLASS=literal>Animal</tt>, which means that the 
<tt CLASS=literal>Bird[]</tt> type is a subtype of <tt CLASS=literal>Animal[]</tt>. 
In the same way a <tt CLASS=literal>Bird</tt> object can be used 
in place of an <tt CLASS=literal>Animal</tt> object, a <tt CLASS=literal>Bird[]</tt> 
array can be assigned to an <tt CLASS=literal>Animal[]</tt> array: 

<DIV CLASS=programlisting>
<P>
<PRE>
Animal [][] animals; 
Bird [][] birds = new Bird [10][10]; 
birds[0][0] = new Bird(); 
 
// make animals and birds reference the same array object 
animals = birds;   
System.out.println( animals[0][0] );               // prints Bird 
</PRE>
</DIV>

<P CLASS=para>
Because arrays are part of the class hierarchy, we can use <tt CLASS=literal>instanceof</tt> 
to check the type of an array: 

<DIV CLASS=programlisting>
<P>
<PRE>
if ( birds instanceof Animal[][] )                 // yes 
</PRE>
</DIV>

<P CLASS=para>
An array is a subtype of <tt CLASS=literal>Object</tt> and can therefore 
be assigned to <tt CLASS=literal>Object</tt> type variables: 

<DIV CLASS=programlisting>
<P>
<PRE>
Object something; 
something = animals; 
</PRE>
</DIV>

<P CLASS=para>
Since Java knows the actual type of all objects, you can also cast back 
if appropriate: 

<DIV CLASS=programlisting>
<P>
<PRE>
animals = (Animal [][])something; 
</PRE>
</DIV>

<P CLASS=para>
Under unusual circumstances, Java may not be able to check the types
of objects you place into arrays at compile-time. In those cases, it's
possible to receive an <tt CLASS=literal>ArrayStoreException</tt> if you
try to assign the wrong type of object to an array element. Consider
the following:

<DIV CLASS=programlisting>
<P>
<PRE>
class Dog { ... } 
class Poodle extends Dog { ... } 
class Chihuahua extends Dog { ... } 
 
Dog [] dogs; 
Poodle [] poodles = new Poodle [10]; 
 
dogs = poodles;  
 
dogs[3] = new Chihuahua();     // Run-time error, ArrayStoreException 
</PRE>
</DIV>

<P CLASS=para>
Both <tt CLASS=literal>Poodle</tt> and <tt CLASS=literal>Chihuahua</tt> are
subclasses of <tt CLASS=literal>Dog</tt>, so an array of
<tt CLASS=literal>Poodle</tt> objects can therefore be assigned to an
array of <tt CLASS=literal>Dog</tt> objects, as I described
previously. The problem is that an object assignable to an
element of an array of type <tt CLASS=literal>Dog[]</tt> may not be
assignable to an element of an array of type
<tt CLASS=literal>Poodle</tt>. A <tt CLASS=literal>Chihuahua</tt> object, for
instance, can be assigned to a <tt CLASS=literal>Dog</tt> element because
it's a subtype of <tt CLASS=literal>Dog</tt>, but not to a
<tt CLASS=literal>Poodle</tt> element.[6]

<blockquote class=footnote>
<P CLASS=para>[6] 
In some sense this could be considered a tiny hole in the Java type 
system. It doesn't occur elsewhere in Java, only with arrays. This is 
because array objects exhibit <I CLASS=emphasis>covariance</I> in 
overriding their assignment and extraction methods. Covariance allows array 
subclasses to override methods with arguments or return values that are 
subtypes of the overridden methods, where the methods would normally be 
overloaded or prohibited. This allows array subclasses to operate on their 
base types with type safety, but also means that subclasses have different 
capabilities than their parents, leading to the problem shown above. 
</blockquote>
</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_07.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch05_09.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Variable and Method Visibility</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Inner Classes</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
